﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FreeSwitch.EventSocket.Parser;

namespace FreeSwitch.EventSocket.Commands
{
	/// <summary>
	/// Generic implementation of a command reply.
	/// </summary>
	/// <remarks>
	/// Checks if the first character in the reply is + or - to determine if the
	/// command was successful or not. Word two and everything else is put in Message property.
	/// </remarks>
	class CommandReply : ICommandReply
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="CommandReply"/> class.
		/// </summary>
		public CommandReply()
		{
			
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="CommandReply"/> class.
		/// </summary>
		/// <param name="success">if set to <c>true</c> [success].</param>
		public CommandReply(bool success)
		{
			Success = success;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="CommandReply"/> class.
		/// </summary>
		/// <param name="success">if set to <c>true</c> [success].</param>
		/// <param name="message">Reply message.</param>
		public CommandReply(bool success, string message)
		{
			Success = success;
			Message = message;
		}

		/// <summary>
		/// Gets or sets whether the command was successful.
		/// </summary>
		public bool Success
		{
			get; private set;
		}

		/// <summary>
		/// Gets or sets message.
		/// </summary>
		public string Message { get; private set; }

		public static CommandReply Parse(ParsedMessage message)
		{
			CommandReply reply = new CommandReply();

			string replyText = message.Headers["reply-text"] ?? "+OK"; 
			reply.Success = replyText.StartsWith("+");

			string body = message.Body.ToString();
			if (!string.IsNullOrEmpty(body))
				reply.Message = body;
			else
			{
				int pos = replyText.IndexOf(' ');
				if (pos != -1)
					reply.Message = replyText.Substring(pos + 1);
			}

			return reply;
		}
	}
}
